﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace MishraReader.Entities.Tools
{
    public static class HtmlTagCleaner
    {
        private static readonly Regex ProcessAllTagsRegex = new Regex(@"<(?<tag>\w*?)\s?.*?>(?<text>.*?)</\k<tag>>",
                                                                      RegexOptions.Singleline);

        private static readonly Regex ProcessAllUnaryTagsRegex = new Regex(@"<(?<tag>\w*?)\s?.*?>",
                                                                           RegexOptions.Singleline);

        private static readonly Regex ProcessAllUnfinishedUnaryTagsRegex = new Regex(@"<(?<tag>\w*?)\s?.*?$",
                                                                                     RegexOptions.Singleline);


        public static string KillTag(string tagName, string data)
        {
            var regex = new Regex(string.Format(@"<(?<tag>{0})\s?.*?>(?<text>.*?)</{0}>", tagName),
                                  RegexOptions.Singleline);

            return regex.Replace(data, "");
        }

        public static string ProcessAllTags(string data)
        {
            return ProcessAllTagsRegex.Replace(data, "${text}");
        }

        public static string ProcessAllUnaryTags(string data)
        {
            data = ProcessAllUnaryTagsRegex.Replace(data, "");
            return ProcessAllUnfinishedUnaryTagsRegex.Replace(data, "");
        }

        public static string ProcessTag(string tagName, string data, string add = "")
        {
            var regex = new Regex(string.Format(@"<(?<tag>{0})\s?.*?>(?<text>.*?)</{0}>", tagName),
                                  RegexOptions.Singleline);

            return regex.Replace(data, "${text}" + add);
        }

        public static string ProcessUnaryTag(string tagName, string data, string add = "")
        {
            var regex = new Regex(string.Format(@"<(?<tag>{0})\s?.*?>", tagName), RegexOptions.Singleline);

            return regex.Replace(data, add);
        }
    }
}